package com.loan.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.loan.common.constant.UserConstants;
import com.loan.common.core.domain.entity.SysDept;
import com.loan.common.enums.DelFlagEnum;
import com.loan.common.exception.ServiceException;
import com.loan.common.utils.StringUtils;
import com.loan.common.utils.TreeBuildUtils;
import com.loan.system.domain.AddressEntity;
import com.loan.system.domain.SysConfig;
import com.loan.system.mapper.AddressMapper;
import com.loan.system.service.AddressService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author shiguang on 2022/9/5 9:31
 */
@RequiredArgsConstructor
@Service
public class AddressServiceImpl implements AddressService {

    private final AddressMapper addressMapper;

    /**
     * 保存地址信息
     *
     * @param name     名称
     * @param parentId 父id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(String name, Long parentId) {
        AddressEntity entity = new AddressEntity();
        entity.setName(name);
        if(parentId != null){
            AddressEntity addressEntity = addressMapper.selectById(parentId);
            if (addressEntity == null){
                throw new ServiceException("父类不存在");
            }
            entity.setParentId(parentId);
        }
        return addressMapper.insert(entity);
    }

    /**
     * 获取所有父类
     * @return
     */
    @Override
    public List<AddressEntity> getParentList(){
        return addressMapper.selectList(new QueryWrapper<AddressEntity>().eq("parent_id","0").eq("del_flag",DelFlagEnum.NORMAL.value()).orderByAsc("name"));
    }

    /**
     * 验证地址名称是否重复
     * @param entity
     * @return
     */
    @Override
    public String checkNameUnique(AddressEntity entity) {
        Long id = ObjectUtil.isNull(entity.getId()) ? -1L : entity.getId();
        AddressEntity addressEntity = addressMapper.selectOne(new LambdaQueryWrapper<AddressEntity>().eq(AddressEntity::getName, entity.getName()));
        if (ObjectUtil.isNotNull(addressEntity) && addressEntity.getId().longValue() != id.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int insertAddress(AddressEntity entity) {
        if (entity.getParentId() != 0){
            //查找当前地址子类最大的code值
            AddressEntity addressEntity = addressMapper.selectVoById(entity.getParentId());
            String code = addressMapper.selectMaxByParentCode(addressEntity.getCode());
            Integer aCode = Integer.valueOf(code) + 1;
            entity.setCode(aCode.toString());
            entity.setAncestors("0," + entity.getParentId());
        }
        return addressMapper.insert(entity);
    }

    /**
     * 根据名称查询是否存在
     * @param name
     * @return
     */
    @Override
    public AddressEntity selectByName(String name) {
        return addressMapper.selectByName(name);
    }

    /**
     * 根据code查询是否存在
     * @param code
     * @return
     */
    @Override
    public AddressEntity selectByCode(String code) {
        return addressMapper.selectByCode(code);
    }

    @Override
    public void updateAddress(AddressEntity address) {
        addressMapper.updateById(address);
    }

    @Override
    public List<AddressEntity> selectAddressList(AddressEntity address) {
        LambdaQueryWrapper<AddressEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressEntity::getDelFlag,DelFlagEnum.NORMAL.value())
                .eq(ObjectUtil.isNotNull(address.getId()), AddressEntity::getId, address.getId())
                .eq(ObjectUtil.isNotNull(address.getParentId()), AddressEntity::getParentId, address.getParentId())
                .like(StringUtils.isNotBlank(address.getName()), AddressEntity::getName, address.getName())
                .orderByAsc(AddressEntity::getParentId);
        return addressMapper.selectAddressList(lqw);

    }

    /**
     * 根据ID获取地址详情
     * @param id
     * @return
     */
    @Override
    public AddressEntity selectAddressById(Long id) {
        return addressMapper.selectById(id);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param list 地址列表
     * @return
     */
    @Override
    public List<Tree<Long>> buildAddressTreeSelect(List<AddressEntity> list) {
        if (CollUtil.isEmpty(list)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(list, (address, tree) ->
                tree.setId(address.getId())
                        .setParentId(address.getParentId())
                        .setName(address.getName())
                        );
    }

    @Override
    public int deleteAddressById(Long id) {
        return addressMapper.deleteById(id);
    }
}
